package fdoj.eventInvitations.servlet;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.Iterator;
import java.util.List;
import java.util.UUID;

import javax.ejb.EJB;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.fileupload.FileItem;

import fdoj.eventInvitations.dao.EventDao;
import fdoj.eventInvitations.dao.PersonDao;
import fdoj.eventInvitations.entity.Contact;
import fdoj.eventInvitations.entity.Event;
import fdoj.eventInvitations.entity.Invantation;
import fdoj.eventInvitations.entity.Person;
import fdoj.eventInvitations.entity.Response;
import fdoj.eventInvitations.util.SendMail;

public class AddEventController extends HttpServlet {
	@EJB
	private PersonDao personDao;

	@EJB
	private EventDao eventDao;

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		doPost(req, resp);
	}

	@Override
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		try {
			HttpSession session = request.getSession(true);
			Person person = (Person) session.getAttribute("loggedUser");
			if (person != null) {
				
				SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy hh:mm");
				Event event = new Event();
				
				String title = request.getParameter("title");
				String description = request.getParameter("description");
				String startTime = request.getParameter("startTime");
				String startDate = request.getParameter("startDate");
				
				String place = request.getParameter("place");
				if(request.getParameter("endCheck")!=null){
				String durationTime = request.getParameter("endTime");
				String durationDate = request.getParameter("endDate");
				if(durationDate != null){
					durationDate += " " + durationTime;
					Date duration = sdf.parse(durationDate);
					event.setEndTime(duration);
				}
				}
				if(request.getParameter("answerCheck")!=null){
				String checkTime = request.getParameter("answerTime");
				String checkDate = request.getParameter("answerDate");
				if(checkDate != null){
					checkDate += " " + checkTime;
					System.out.println(checkDate);
					Date check = sdf.parse(checkDate);
					event.setCheckTime(check);
				}
				}
				
				FileItem item = (FileItem) request.getAttribute("file");
				String image = saveToDrive(item);
				
				
				String[] contacts_id = request.getParameterValues("contact");
				event.setTitle(title);
				event.setDescription(description);			
				event.setPlace(place);
				event.setCanceled(false);					
				event.setImage(image);																		
				

				if(startDate != null){
					startDate += " " + startTime;
					Date start = sdf.parse(startDate);
					System.out.println(start);
					event.setStartTime(start);
				}
;
				
				

				

				if (contacts_id != null && !contacts_id.equals(""))
					for (int i = 0; i < contacts_id.length; i++) {
						Invantation invite = new Invantation();
						invite.setStatus(Response.NON_RESPONSE);
						invite.setEvent(event);
						List<Contact> contacts = (List<Contact>) session
								.getAttribute("contacts");
						for (Contact c : contacts) {
							if (c.getId() == Integer.parseInt(contacts_id[i])) {
								invite.setEventCall(c);
								c.addInvites(invite);
								event.addInvitation(invite);
								
								break;
							}
						}
					}
				Person loggedUser = personDao.findById(person.getId());
				loggedUser.addEvent(event);
				
				// eventDao.merge(event);
				//Event ev = eventDao.merge(event);
				
				for(Invantation i : event.getInvitations()){
					String subject = "Pozivnica za dogadjaj";
					String text = "Dobili ste poziv za event," +
							" pogledajte na sledecoj adresi: http://localhost:8080/PozivNaDogadjaj/answer?inv_id="+ i.getId()
							+"&st="+i.getSecurityToken();
					SendMail sm = new SendMail();
					sm.Send(i.getEventCall().getEmail(), text, subject);
				}
				personDao.merge(loggedUser);
				
				session.setAttribute("loggedUser", loggedUser);
				response.sendRedirect(response.encodeRedirectURL("./home"));
				return;
			} else {
				response.sendRedirect(response.encodeRedirectURL("./index"));
				return;
			}
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
		response.sendRedirect(response.encodeRedirectURL("./index"));

	}

	private String saveToDrive(FileItem item) throws Exception {
		
		if (item != null) {
			UUID uuid = UUID.randomUUID();
			String picture = uuid.toString();
			File dir = new File(getServletContext().getRealPath("")
					+ "/images/");
			if (!dir.exists()) {
				dir.mkdirs();
			}
			File f = new File(getServletContext().getRealPath("") + "/images/"
					+ picture + ".jpg");
			item.write(f);
			return f.getName();
		}
		return null;
	}

}
